import { defineStore } from 'pinia'
// // 登录回去用户token接口
import { getTokenAPI, getUserInfoAPI, loginOutAPI } from '@/apis/user'
import { ref } from 'vue'
// 路由信息
import { constRouter } from '@/router/router'

// 过滤出当前用户所需要的异步路由
const filterAsyncRouter = (asyncRoute: any, routes: any) => {
	return asyncRoute.filter((item: any) => {
		if (routes.includes(item.name)) {
			if (item.children && item.children.length > 0) {
				item.children = filterAsyncRouter(item.children, routes)
			}
			return true
		}
	})
}

export const useUserStore = defineStore(
	'user',
	() => {
		// 用户token
		const token = ref(null)
		// 左侧菜单需要渲染的数据
		const menuRouter = constRouter
		// 用户信息
		const userInfo = ref<any>({
			name: '',
			avatar: ''
		})

		const userLogin = async (data: Object) => {
			const res = await getTokenAPI(data)
			token.value = res.data
			return token.value
		}

		// const changeRouter = () => {
		// 	const routerUser = filterAsyncRouter(cloneDeep(asyncRouter) , userInfo.value.routes)
		// 	menuRouter.value = [...constRouter, ...routerUser, ...anyRouter]
		// 	const routerAdd = [...routerUser, ...anyRouter]
		// 	routerAdd.forEach((route: any) => {
		// 		router.addRoute(route)
		// 	})
		// }

		// 获取用户信息
		const getUserInfo = async () => {
			const res = await getUserInfoAPI()
			userInfo.value = res.data
			// changeRouter()
		}

		// 退出登录
		const logout = async () => {
			// 退出登录接口
			// await loginOutAPI()
			// token.value = null
			// userInfo.value = {
			// 	name: '',
			// 	avatar: ''
			// }

			localStorage.removeItem('user')
		}

		return { token, menuRouter, userLogin, userInfo, getUserInfo, logout }
	},
	{
		// pinia持久化存储插件
		persist: true
	}
)
